﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.Management.Automation;
using Microsoft.ApplicationServer.Caching.AdminApi;

namespace AppFabricAdministrator
{
    public partial class NamedCaches : UserControl
    {
        private NamedCaches()
        {
            InitializeComponent();
            this.cmbNamedCaches.Items.AddRange(ListNamedCaches().ToArray());
        }
        private static NamedCaches namedCacheControl;
        public static NamedCaches GetCurrentNamedCaches(bool forceGet)
        {
            if(namedCacheControl==null || forceGet)
                namedCacheControl=new NamedCaches();
            return namedCacheControl;
        }
        public static void Flush()
        {
            namedCacheControl = null;
        }
        private void NamedCaches_Load(object sender, EventArgs e)
        {
          // this.cmbNamedCaches.Items.Clear();
          //  this.cmbNamedCaches.Items.AddRange(ListNamedCaches().ToArray());

        }
        public string SelectedNamedCache
        {
            get
            {
                return cmbNamedCaches.SelectedItem == null ? null : cmbNamedCaches.SelectedItem.ToString();
            }
        }
        public void UpdateNamedCaches()
        {
            this.cmbNamedCaches.Items.Clear();
            this.cmbNamedCaches.Text = "";
            this.cmbNamedCaches.Items.AddRange(ListNamedCaches().ToArray());
        }
        private List<string> namedCaches;
        private List<string> ListNamedCaches()
        {
            var getCacheCmd = "Get-Cache";
            bool isSuccess = false;
            ScriptHelper.RunScript(getCacheCmd, "",GetNamedCache, out isSuccess);
            return namedCaches;
        }

        public string GetNamedCache(IEnumerable<PSObject> results)
        {
            StringBuilder resultString = new StringBuilder();
            namedCaches = new List<string>();
            foreach (var res in results)
            {
                CacheInfo ci = (CacheInfo)res.BaseObject;
                namedCaches.Add(ci.CacheName);
                resultString.AppendLine(ci.CacheName);
            }
            return resultString.ToString();
        }

    }
}
